<?php

namespace common\models\user;

use Yii;
use common\models\shop\ShopCoupon;
use common\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%user_coupon}}".
 *
 * @property int $id
 * @property int $user_id
 * @property int $coupon_id
 * @property string $model
 * @property int $model_id
 * @property int $status
 * @property int $expired_at
 * @property int $created_at
 * @property int $updated_at
 * @property int $deleted_at
 */
class UserCoupon extends \common\db\ActiveRecord {

    const STATUS_USED = 10;
    const STATUS_ACTIVE = 1;
    const STATUS_DEFAULT = 0;
    const MODEL_SHOP_ORDER = 'ShopOrder';

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%user_coupon}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['user_id', 'coupon_id', 'model_id', 'status', 'expired_at', 'created_at', 'updated_at', 'deleted_at'], 'integer'],
            [['model'], 'string', 'max' => 20],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'user_id' => 'User ID',
            'coupon_id' => 'Coupon ID',
            'model' => 'Model',
            'model_id' => 'Model ID',
            'status' => 'Status',
            'expired_at' => 'Expired At',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
            'deleted_at' => 'Deleted At',
        ];
    }

    public function getCoupon() {
        return $this->hasOne(ShopCoupon::class, ['id' => 'coupon_id']);
    }

    public static function findAvailable($uid, $type) {
        $query = static::find()->alias('t')->active()->andWhere([
            'and',
            ['t.user_id' => $uid],
            ['t.status' => static::STATUS_DEFAULT],
            ['>=', 't.expired_at', time()]
        ]);
        $query->innerJoinWith('coupon c');
        if ($type == 'value') {
            $query->andWhere([
                'and',
                ['c.unit' => ShopCoupon::UNIT_VALUE],
                ['>', 'c.discount', 0],
            ]);
        } else {
            $query->andWhere([
                'and',
                ['c.unit' => ShopCoupon::UNIT_RATIO],
                ['>', 'c.radix', 0],
            ]);
        }
        return $query;
    }

    public static function findDiscounts($uid) {
        $query = static::findAvailable($uid, 'value');
        return $query->all();
    }

    public static function findDiscountValue($uid) {
        $data = static::findDiscounts($uid);
        if (empty($data)) {
            return 0;
        }
        $discounts = [];
        foreach ($data as $item) {
            $discounts[$item->id] = $item->coupon->discount;
        }
        return $discounts;
    }

}
